//let body = document.getElementById( 'body' );
//body.innerHTML = '<div style="height: 100%;" ><canvas id= "canvas" > Your browser does not support canvas element. </canvas></div>';
//let l1 = window.screen.width;
//let l2 = window.screen.height;
//console.log(l1,l2);
//let width;
//let height;
//let canvas = document.getElementById('canvas');
//canvas.setAttribute("style","cursor: default; background-color: #555555;height: 100%;width:100%");
//canvas.setAttribute("width",l1);
//canvas.setAttribute("height",l2);
//console.log(canvas.width);
//console.log(canvas.height);






class Frame{
  pageW;
  pageH;

  screenW;
  screenH;
  
  isMobile = false;

  drawor;
  pip;

  constructor(){
    this.initPage();
    this.drawor = new Drawor();
    this.pip = new Pip();
    let assets = new Assets();
    this.pip.assets = assets;
    this.drawor.assets = assets;
    this.drawor.screenW = this.screenW;
    this.drawor.screenH = this.screenH;
    console.log("swh ",this.screenW , this.screenH)
    this.drawor.pip = this.pip;
    this.drawor.assets = assets;
    this.drawor.init();
    this.finish();
  }

  initPage(){
    let body = document.body;
    this.pageW = window.screen.width;
    this.pageH = window.screen.height;

    this.screenW = screen.width;
    this.screenH = screen.height;

    if(this.pageW < this.pageH){
        this.isMobile = true;
    }

    body.innerHTML = "";
    body.style.setProperty("background-color","#000000");
    body.style.setProperty("margin",0);


    body.innerHTML = body.innerHTML+"<canvas id = 'canvas' ></canvas>"
    body.innerHTML = body.innerHTML+"<button id = 'fullBt'>FullSCR</canvas>"

    let fullBt = document.getElementById("fullBt");
    fullBt.onclick=()=>{this.drawor.fullScreen();};

    let canvas = document.getElementById("canvas");
    canvas.style.setProperty("display","none");

    document.addEventListener('fullscreenchange', function() {
      if (document.fullscreenElement) {
        console.log('进入全屏模式');
      } else {
        console.log('退出全屏模式');
        canvas.style.setProperty("display","none");
      }
    });
  }

  finish(){
    console.log(this.pageW,this.pageH,this.screenW,this.screenH,this.isMobile);
  }


}

class Drawor{
  frame;
  canvas;
  ctx;
  
  assets;
  pip;

  screenW;
  screenH;
  canvasSmall=400;
  canvasW;
  canvasH;
  ongoingTouches={};
  
  logstr;

  constructor(){
    this.canvas = document.getElementById('canvas');
    this.ctx = this.canvas.getContext("2d");
    this.setEventListener();
  }

  init(){
    if(this.screenW < this.screenH){
      let tem = this.screenH;
      this.screenH = this.screenW;
      this.screenW = tem;
    } 
    
    this.canvasH = this.canvasSmall;
    this.canvasW = this.screenW/this.screenH*this.canvasSmall;
    
    this.canvas.width = this.canvasW;
    this.canvas.height = this.canvasH;


    let mvbut = new Button();
    mvbut.pip = this.pip;
    this.assets.buttons.mvbut=mvbut;

    let atbut = new AtButton();
    atbut.pip = this.pip;
    atbut.locX = this.canvasW-atbut.effectiveW;
    this.assets.buttons.atbut=atbut;
  }


  fullScreen(){
    console.log("fullScreen");
    this.pip.send("full screen");

    let cmd1 = {"type":"croom"};
    this.pip.send(JSON.stringify(cmd1));

    let cmd = {"type":"startg"};
    this.pip.send(JSON.stringify(cmd));

    this.canvas.requestFullscreen = canvas.requestFullscreen || canvas.webkitRequestFullscreen || canvas.msRequestFullscreen;
    this.canvas.requestFullscreen();
//    if(this.screenW < this.screenH){
//      this.canvas.width = this.screenH/this.screenW*this.canvasSmall;
//      this.canvas.height = this.canvasSmall;
//    }else{
//      this.canvas.width = this.screenW/this.screenH*this.canvasSmall;
//      this.canvas.height = this.canvasSmall;
//    }
    this.canvas.style.setProperty("display","block");
    this.canvas.style.setProperty("background-color","#333333ff");
    this.draw();
  }

  exitFullScreen(){
    this.canvas.exitFullscreen = canvasexitFullscreen || canvas.webkitExitFullscreen || canvas.mozCancelFullScreen || canvas.msExitFullscreen;
    this.canvas.exitFullscreen();
  }

  addTouch(touch){
    this.ongoingTouches["tc"+touch.identifier] = {x:touch.pageX,y:touch.pageY};
  }

  findTouch(touch){
    return this.ongoingTouches["tc"+touch.identifier];
  }

  removeTouch(touch){
    delete this.ongoingTouches["tc"+touch.identifier];
  }

  bindButtonTouch(button,touch){
    let etouch = this.ongoingTouches["tc"+touch.identifier];
    button.touch = etouch;
    etouch.button = button;
  }

  getButton(x,y){
    for (let key in this.assets.buttons){
      let button = this.assets.buttons[key];
      if(button.locX < x && button.locY < y && button.locX + button.effectiveW > x && button.locY + button.effectiveH > y ){
        return button;
      }
    }
  }

  setEventListener(){
    let that = this;
    let canvas = this.canvas;
    canvas.addEventListener( "touchstart" , function(evt){
      evt.preventDefault();  //阻止事件的默认行为
      let touches = evt.changedTouches;
        for ( let  i=0; i < touches.length; i++) {
          that.addTouch(touches[i]);
          let x = touches[i].pageX/that.screenW*that.canvas.width;
          let y = touches[i].pageY/that.screenH*that.canvas.height;
          let button = that.getButton(x,y);
          if(!button){
            return;
          }
          that.bindButtonTouch(button,touches[i]);
          let etouch = that.findTouch(touches[i]);
          etouch.px = x;
          etouch.py = y;
          button.press(x,y);
      }
    },  false );

    canvas.addEventListener( "touchmove" , function(evt){
      evt.preventDefault();  //阻止事件的默认行为
      let touches = evt.changedTouches;
        for ( let  i=0; i < touches.length; i++) {
          let x = touches[i].pageX/that.screenW*that.canvas.width;
          let y = touches[i].pageY/that.screenH*that.canvas.height;
          let etouch = that.findTouch(touches[i]);
          etouch.mx=x;
          etouch.my=y;
          if(etouch.button){
            etouch.button.move(x,y);
          }
      }
    },  false );
    canvas.addEventListener( "touchend" , function(evt){
      evt.preventDefault();  //阻止事件的默认行为
      let touches = evt.changedTouches;
        for ( let  i=0; i < touches.length; i++) {
          let x = touches[i].pageX/that.screenW*that.canvas.width;
          let y = touches[i].pageY/that.screenH*that.canvas.height;
          let etouch = that.findTouch(touches[i]);
          if(etouch.button){
            etouch.button.release(x,y);
          }
          that.removeTouch(touches[i]);
      }
    },  false );
  }

  draw(){
    this.ctx.fillStyle = "#ffffff";
    this.ctx.fillRect(0, 0, this.canvas.width, this.canvas.height);
   // this.ctx.fillStyle = "#ff3333";
   // this.ctx.fillRect(this.canvas.width/2, 0, this.canvas.width/2, this.canvas.height);
   // this.ctx.fillStyle = "#00000088";
   // this.ctx.fillRect(0, 0, this.canvas.width, this.canvas.height);
   // this.ctx.globalCompositeOperation = "source-out";
   // this.ctx.beginPath();
   // this.ctx.arc(400,200,100,1,Math.PI,true);
   // this.ctx.fill();
   // this.ctx.globalCompositeOperation = "source-over";
    
    for(let key in this.assets.buttons){
      let button = this.assets.buttons[key];
      this.drawShape(button.shape);
    }
    for(let i in this.assets.eles.roles){
      this.drawShape(this.assets.eles.roles[i].shape);
    }
    window.requestAnimationFrame(()=>{this.draw()});
  }

  drawShape(shape){
    let type = shape.type;
    if(type == "list"){
      for(let i in shape.child){
        this.drawShape(shape.child[i]);
      }
    }else if(type == "circle"){
      this.drawCircle(shape);
    }
  }

  drawCircle(c){
    let ctx = this.ctx;
    ctx.fillStyle = c.color;
    ctx.beginPath();
    ctx.arc(c.x, c.y, c.r, 0,2*Math.PI,  false );   // a circle at the start
    ctx.fill();
  }
}


class Assets{
  buttons={};
  eles={};
  constructor(){
    this.eles.roles = {};
  }
}


class Pip{
  ws;
  assets;
  name = "pip";

  constructor(){
    let that = this;
    let host = window.location.host;
    this.ws = new WebSocket("ws://"+host+"/ws"); 
    this.ws.onmessage=function(msg){that.receive(msg)}
  }

  send(msg){
    this.ws.send(msg);
  }

  sendCmd(cmd){
    this.ws.send(JSON.stringify(cmd));
  }
  receive(msg){
    // console.log("receive msg " + msg.data);
    let cmd;
    try{
      cmd = JSON.parse(msg.data);
    }catch(e){
      console.log("receive error " + e.message);
      return;
    }
    if(cmd.type == "uiEle"){
      for( let i in cmd.data){
        let ele = cmd.data[i];
        if(ele.type == "role"){
          this.assets.eles.roles[ele.id] = ele;
        }
      }
    }
  }

}


class Button{
  pip;
  touch;
  shape = {
    type:"list",
    child:[
    ]
  };
  effectiveW = 200;
  effectiveH = 200;
  
  locX=0;
  locY=200;

  state = 0;

  constructor(pip){
    this.pip = pip;
  }
  press(x,y){
    console.log("press mvbut " , x ,y);
    if(this.state == 1){
      return;
    }
    this.shape.child.pop();
    this.state = 1;
    this.shape.child.push(
      {
        type:"circle",
        r:10,
        color:"#55559999",
        x:x,
        y:y
      }
    );
  }

  move(tx,ty){
    if(this.shape.child.length > 1){
      this.shape.child.pop();
    }
    this.shape.child.push(
      {
        type:"circle",
        r:10,
        color:"#55ff5599",
        x:tx,
        y:ty
      }
    );
    let cmd = {"type":"move","dx":tx-this.touch.px,"dy":ty-this.touch.py};
    this.pip.send(JSON.stringify(cmd));
  }
 
  release(x,y){
    console.log("release but ",x,y);
    this.state = 0;
    this.shape.child=[];
    
    let cmd = {"type":"stop"};
    this.pip.send(JSON.stringify(cmd));
  }

}



class AtButton{
  pip;
  touch;
  shape = {
    type:"list",
    child:[
    ]
  };
  effectiveW = 200;
  effectiveH = 200;
  
  locX=0;
  locY=200;

  state = 0;

  constructor(pip){
    this.pip = pip;
  }
  press(x,y){
    console.log("press mvbut " , x ,y);
    if(this.state == 1){
      return;
    }
    this.shape.child.pop();
    this.state = 1;
    this.shape.child.push(
      {
        type:"circle",
        r:10,
        color:"#55559933",
        x:x,
        y:y
      }
    );
  }

  move(tx,ty){
    if(this.shape.child.length > 1){
      this.shape.child.pop();
    }
    this.shape.child.push(
      {
        type:"circle",
        r:10,
        color:"#55ff5533",
        x:tx,
        y:ty
      }
    );
    console.log("attack " , this.touch.x , this.touch.y , this.touch.mx, this.touch.my);
    let cmd = {"type":"attack","dx":tx-this.touch.x,"dy":ty-this.touch.y};
    this.pip.send(JSON.stringify(cmd));
  }

  release(x,y){
    console.log("release but ",x,y);
    this.state = 0;
    this.shape.child=[];
  }
} 


class Ele{
  type="circle";
  r=50;
  color="#ffff5511";
  x = 400;
  y = 200;
}
















let frame = new Frame();
//let dw = new Drawor();
//dw.fullScreen();










